package com.my.study.snakeyaml;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * Yaml测试
 *
 * @author: yidujun
 * @create: 2021/03/31 23:06
 */
@Slf4j
public class YamlTest {

    @Test
    public void test01() {
        Yaml yaml = new Yaml();
        String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae";
        List<String> load = yaml.load(document);
        System.out.println(load);
    }

    /**
     * 加载多个文档
     */
    @Test
    public void test02() throws IOException {
        ClassPathResource resource = new ClassPathResource("example2_28.yaml");
        InputStream stream = resource.getInputStream();
        Yaml yaml = new Yaml();
        for (Object data : yaml.loadAll(stream)) {
            System.out.println(data);
        }
    }

    @Test
    public void test03() throws IOException {
        ClassPathResource resource = new ClassPathResource("any-object-example.yaml");
        InputStream stream = resource.getInputStream();
        String doc = IOUtils.toString(stream, String.valueOf(StandardCharsets.UTF_8));
        Yaml yaml = new Yaml();
        Map<String, Object> load = yaml.load(doc);
        System.out.println(load);
    }

    @Test
    public void testYamlParser() throws IOException {
        String document = "\n- Hesperiidae\n- Papilionidae\n- Apatelodidae\n- Epiplemidae";
        List<String> list = YamlParser.loadObject(document, List.class);
        System.out.println(list);

        String dumpObject = YamlParser.dumpObject(list);
        System.out.println(dumpObject);

        ClassPathResource resource = new ClassPathResource("any-object-example.yaml");
        InputStream stream = resource.getInputStream();
        Object object = YamlParser.loadObject(stream, Map.class);
        System.out.println(object);
    }

}
